package com.qlu.casualtalk.server;

import com.qlu.casualtalk.constant.JwtConstant;
import com.qlu.casualtalk.domain.dto.UserRegistrationDTO;
import com.qlu.casualtalk.domain.po.User;
import com.qlu.casualtalk.domain.vo.UserBasicInfoVO;
import com.qlu.casualtalk.mapper.UserMapper;
import com.qlu.casualtalk.util.JwtUtil;
import com.qlu.casualtalk.util.Md5Util;
import com.qlu.casualtalk.util.ThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class UserService {

    private final UserMapper userMapper;

    public User findUserByAccount(String account) {
        return userMapper.findUserByAccount(account);
    }

    public User findUserByPhone(String phone) {
        return userMapper.findUserByPhone(phone);
    }

    public User findUserByEmail(String email) {
        return userMapper.findUserByEmail(email);
    }

    public void register(UserRegistrationDTO userRegistrationDTO) {
        User user= new User();
        BeanUtils.copyProperties(userRegistrationDTO,user);
        user.setPassword(Md5Util.getMD5String(user.getPassword()));
        userMapper.insert(user);
    }

    public String login(User user) {
        // 更新最后登录时间
        user.setLastLogin(LocalDateTime.now());
        userMapper.updateById(user);
        // 生成token
        Map<String,Object> map=new HashMap<>();
        map.put(JwtConstant.userIdInThreadLocal,user.getId());
        map.put(JwtConstant.userAccountInThreadLocal,user.getAccount());
        // 返回token
        return JwtUtil.genToken(map);
    }

    public User findUserById(Integer id) {
        return userMapper.findUserById(id);
    }

    public void updateUserInfo(String item, String value) {
        User user=new User();
        user.setId(getUserId());
    }

    private Integer getUserId() {
       Map<String,Object> o = ThreadLocalUtil.get();
       return (Integer) o.get(JwtConstant.userIdInThreadLocal);
    }

    public UserBasicInfoVO getUserBasicInfo() {
        Integer id=getUserId();
        User user=userMapper.findUserById(id);
        UserBasicInfoVO userBasicInfoVO=new UserBasicInfoVO();
        BeanUtils.copyProperties(user,userBasicInfoVO);
        return userBasicInfoVO;
    }
}
